<?php
// 过程化开发分页功能

include 'config.php';

// 数据库查询求和
$sqlCount="select count(*) from user";
$rstCount=$mysqli->query($sqlCount);

// 从结果集中取得一行作为枚举数组
$rowCount=$rstCount->fetch_row();

// 总数
$total=$rowCount[0];

// 每页个数
$length=2;

// 总页数
$pagenum=ceil($total/$length);

// 计算当前页数
$page=isset($_GET['p'])?$_GET['p']:1;

// 计算offset
$offset=($page-1)*$length;

// 输出每页的数据
$sqlUser="select * from user order by id limit $offset,$length";
$rstUser=$mysqli->query($sqlUser);

// 计算上一页
if($page<=1){
	$prevpage=$page;
}else{
	$prevpage=$page-1;
}

// 计算下一页
if($page>=$pagenum){
	$nextpage=$pagenum;
}else{
	$nextpage=$page+1;
}

?>

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>分页</title>
</head>
<body>
	<center>
		<h3>分页</h3>
		<table border="1" cellspacing="0" width="600px">
			<tr>
				<th>ID</th>
				<th>用户名</th>
				<th>密码</th>
				<th>注册时间</th>
			</tr>
			<?php
				while ($rowUser=$rstUser->fetch_assoc()) {
					echo "<tr>";
					echo "<td>{$rowUser['id']}</td>";
					echo "<td>{$rowUser['username']}</td>";
					echo "<td>{$rowUser['password']}</td>";
					echo "<td>".date('Y-m-d H:i:s',$rowUser['time'])."</td>";
					echo "</tr>";
				}
			?>
		</table>
		<!-- 分页 -->
		<p>
			<a href="index.php?p=1">首页</a> |
			<a href="index.php?p=<?php echo $prevpage?>">上一页</a> |
			<a href="index.php?p=<?php echo $nextpage?>">下一页</a> |
			<a href="index.php?p=<?php echo $pagenum?>">末页</a>
		</p>
	</center>
</body>
</html>